require 'webrick'
include WEBrick

require File.dirname(__FILE__) + "/../common/ItemType"
require File.dirname(__FILE__) + "/../exception/IllegalArgumentException"
require File.dirname(__FILE__) + "/../logic/BudgetSearchAction"
require File.dirname(__FILE__) + "/../logic/CompoundSearchAction"
require File.dirname(__FILE__) + "/../logic/OutgoingSearchAction"
require File.dirname(__FILE__) + "/../logic/SearchActionFactory"
require File.dirname(__FILE__) + "/../request/BudgetQuery"
require File.dirname(__FILE__) + "/../request/CompoundQuery"
require File.dirname(__FILE__) + "/../request/OutgoingQuery"
require File.dirname(__FILE__) + "/../request/RequestType"
require File.dirname(__FILE__) + "/../response/BudgetResult"
require File.dirname(__FILE__) + "/../response/CompoundResult"
require File.dirname(__FILE__) + "/../response/OutgoingResult"

# EasyCashbook サーバの入り口となるサーブレット
class EasyCashbookServlet < WEBrick::HTTPServlet::AbstractServlet
  # GET メソッドでサーブレットに接続要求がきた場合の処理  
  def do_GET(req, res)
    res['Content-Type'] = 'text/html'
    res.body = "<html><body>This is EasyCashbookServlet.</body></html>"
  end
  
  # POST メソッドでサーブレットに接続要求がきた場合の処理
  def do_POST(req, res)
    requestType = RequestType.valueOf(req.query["action"]);
    case requestType 
      when RequestType::LOGIN
      login(req, res)
      when RequestType::LOGOUT
      logout(req, res)
      when RequestType::SEARCH
      search(req, res)
      when RequestType::ADD
      add(req, res)
    else
      raise IllegalArgumentException, "request action [" + requestType + "] is not RequestType"
    end
  end
  
  private
  # ログイン処理
  def login(req, res)
    res['Content-Type'] = 'text/html'
    res.body = "<html><body>REQUEST BY POST LOGIN</body></html>"
  end
  
  # ログアウト処理
  def logout(req, res)
    res['Content-Type'] = 'text/html'
    res.body = "<html><body>REQUEST BY POST LOGOUT</body></html>"
  end
  
  # 検索処理
  def search(req, res)
#    res.body = '{"result": {"type": "compound", "rows": [{"budgetId": 0, "budgetName": "娯楽", "budget": 20000, "outgoing": 3000}]}}'
    query = constructQuery(req)
    action = SearchActionFactory.getInstance().createAction(query)
    result = action.execute()
    result.appendResultTo(res)
  end
  
  # HTTPリクエストから、検索リクエストを抽出する
  def constructQuery(req)
    type = ItemType.valueOf(req.query["type"])
    case type
      when ItemType::COMPOUND
      return CompoundQuery.new(req)
      when ItemType::BUDGET
      return BudgetQuery.new(req)
      when ItemType::OUTGOING
      return OutgoingQuery.new(req)
    else
      raise IllegalArgumentException, "request type [" + type + "] is not ItemType"
    end
  end
  
  # 追加処理
  def add(req, res)
    res['Content-Type'] = 'text/html'
    res.body = "<html><body>REQUEST BY POST ADD</body></html>"
  end
  
end